package com.example.deliveryapplication

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.deliveryapplication.entity.Plan
import com.example.deliveryapplication.entity.PlanWithPlanItem
import com.example.deliveryapplication.sql.AppDatabase
import kotlinx.android.synthetic.main.activity_history.*
import kotlinx.android.synthetic.main.item_plan_list.*


class HistoryActivity : AppCompatActivity(),PlanAdapter.CallBack {
    private val mList=ArrayList<PlanWithPlanItem>()
    private val planDao by lazy { AppDatabase.getDatabase(this).planDao() }
    private val planItemDao  by lazy { AppDatabase.getDatabase(this).planItemDao() }
    private val mViewModel by lazy { ViewModelProvider(this)[HistoryViewModel::class.java] }
    private val mAdapter=PlanAdapter(this, mList,this)
    private var selectPosition=-1
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_history)
        mRecycleView.layoutManager=LinearLayoutManager(this)
        mRecycleView.adapter=mAdapter

        mViewModel.getPlanResult.observe(this){list->
            Log.d("测试",list.size.toString())
            mList.addAll(list)
            mAdapter.notifyDataSetChanged()
        }
        mViewModel.deletePlanResult.observe(this){
            if(selectPosition!=-1){
                mAdapter.removeAt(selectPosition,mList.size)
                mList.removeAt(selectPosition)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mList.clear()
        mViewModel.getPlan(planDao)
    }

    override fun onItemDelete(position: Int, data: PlanWithPlanItem) {
        commonDialog("确认删除该条数据么，删除后无法恢复"){
            mViewModel.deletePlan(planDao, planItemDao  ,data.plan)
            selectPosition=position
        }
    }

    override fun onItemCopy(position: Int, data: PlanWithPlanItem) {
        startActivity(Intent(this,NewPlanActivity::class.java).putExtra("whereFrom",2).putExtra("planId",data.plan.id))
    }
}